package org.ishequ.miduo;

import java.util.List;
import org.ishequ.miduo.R;
import org.ishequ.miduo.MiDuoActivity.ConfigHelper;
import org.ishequ.miduo.R.id;
import org.ishequ.miduo.R.layout;
import org.ishequ.miduo.R.string;
import org.ishequ.miduo.R.style;
import org.ishequ.miduo.renren.ApiDemoInvoker;
import org.ishequ.miduo.renren.ApiListActivity;
import org.ishequ.miduo.weibo.WeiboHomeActivity;
import org.ishequ.renren.api.RenrenApiConfig;
import org.ishequ.weibo.adapater.UserAdapater;
import org.ishequ.weibo.db.UserInfoDBHelper;
import org.ishequ.weibo.domain.UserInfo;

import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.view.RenrenAuthListener;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	
	/**
	 * weibo
	 */
	private Dialog dialog;
	private UserInfoDBHelper dbHelper;
	private List<UserInfo> userList;
	private EditText iconSelect;
	private ImageView icon;
	final static String Select_Name = "Select_Name";
	
	/**
	 * renren
	 */
	//你的应用ID 
//	private static final String APP_ID = "200594"; 
	//应用的API Key 
//	private static final String API_KEY = "d5b61d6db130477ab9152131295127c5"; 
	//应用的Secret Key 
//	private static final String SECRET_KEY = "5b564229c62149dfa4f61c02e1eef0a0"; 
	private Renren renren; 
	private Handler handler; 
	private Button loginBtn; 
	private Button logoutBtn; 
	private TextView loginText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weibo_login);

		/**
		 * weibo
		 */
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
		iconSelect = (EditText) findViewById(R.id.iconSelect);
		icon = (ImageView) findViewById(R.id.icon);
		// 背景自动适应
		// AndroidHelper.AutoBackground(this, layout, R.drawable.bg_v,
		// R.drawable.bg_h);
		initUser();

		ImageButton iconSelectBtn = (ImageButton) findViewById(R.id.iconSelectBtn);
		iconSelectBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				View diaView = View.inflate(LoginActivity.this,R.layout.weibo_dialog2, null);
				dialog = new Dialog(LoginActivity.this, R.style.dialog2);
				dialog.setContentView(diaView);
				dialog.show();

				UserAdapater adapater = new UserAdapater(LoginActivity.this ,R.layout.weibo_item_user, userList);
				ListView listview = (ListView) diaView.findViewById(R.id.list);
				listview.setVerticalScrollBarEnabled(false);// ListView去掉下拉条
				listview.setAdapter(adapater);
				// 对登录列表的监听
				listview.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View view,int arg2, long arg3) {
						TextView tv = (TextView) view.findViewById(R.id.showName);
						iconSelect.setText(tv.getText());
						ImageView iv = (ImageView) view.findViewById(R.id.iconImg);
						icon.setImageDrawable(iv.getDrawable());
						dialog.dismiss();
					}
				});
			}
		});
		
		ImageButton login = (ImageButton) findViewById(R.id.login);
		login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				goHome();
			}

		});
		
		/**
		 * renren
		 */
		init(); 
		//登录的Listener 
		final RenrenAuthListener listener = new RenrenAuthListener() { 
			//登录成功 
			public void onComplete(Bundle values) { 
				showLoginBtn(false); 
				loginText.setText(R.string.auth_success); 
				handler.post(new Runnable() { 
					@Override 
					public void run() { 
						Toast.makeText(LoginActivity.this, LoginActivity.this.getString(R.string.auth_success), Toast.LENGTH_SHORT).show(); 
					} 
				}); 
				startApiList();
			} 
			//登录失败
			@Override 
			public void onRenrenAuthError(RenrenAuthError renrenAuthError) { 
				loginText.setText(R.string.auth_failed); 
				handler.post(new Runnable() { 
					@Override 
					public void run() { 
						Toast.makeText(LoginActivity.this, LoginActivity.this.getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); 
					} 
				}); 
			} 
			@Override 
			public void onCancelLogin() { 
				
			} 
			@Override 
			public void onCancelAuth(Bundle values) { 
				
			} 
		}; 
		//登录按钮的事件 
		loginBtn.setOnClickListener(new View.OnClickListener() { 
			@Override 
			public void onClick(View v) { 
				renren.authorize(LoginActivity.this, new String[]{"read_user_feed"}, listener); 
			} 
		}); 
		//退出按钮的事件 
		logoutBtn.setOnClickListener(new View.OnClickListener() { 
			@Override 
			public void onClick(View v) { 
				renren.logout(getApplicationContext()); 
				showLoginBtn(true); 
				loginText.setText(R.string.auth_string); 
			} 
		}); 
	}

	private void initUser() {
		// 获取账号列表
		dbHelper = UserInfoDBHelper.getInstance(this);
		userList = dbHelper.getUserList(false);
		if (userList.isEmpty()) {
			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, AuthorizeActivity.class);
			startActivity(intent);
		} else {
			SharedPreferences preferences = getSharedPreferences(Select_Name,
					Activity.MODE_PRIVATE);
			String str = preferences.getString("name", "");
			UserInfo user = null;
			if (str != "") {
				user = getUserByName(str);
			}
			if (user == null) {
				user = userList.get(0);
			}
			icon.setImageDrawable(user.getUserIcon());
			iconSelect.setText(user.getUserName());
		}
	}

	public UserInfo getUserByName(String name) {
		for (UserInfo u : userList) {
			if (u.getUserName().equals(name)) {
				return u;
			}
		}
		return null;
	}

	// 进入用户首页
	private void goHome() {
		if (userList != null) {
			String name = iconSelect.getText().toString();
			UserInfo u = getUserByName(name);
			if (u != null) {
				ConfigHelper.nowUser = u;// 获取当前选择的用户并且保存
			}
		}
		if (ConfigHelper.nowUser != null) {
			// 进入用户首页
			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, WeiboHomeActivity.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onStop() {
		// 获得SharedPreferences对象
		SharedPreferences MyPreferences = this.getSharedPreferences(Select_Name,Activity.MODE_PRIVATE);
		// 获得SharedPreferences.Editor对象
		SharedPreferences.Editor editor = MyPreferences.edit();
		// 保存组件中的值
		editor.putString("name", iconSelect.getText().toString());
		editor.commit();
		super.onStop();
	}
	
	/**
	 * renren
	 */
	
	//初始化按钮和Renren实例 
	private void init(){
		renren = new Renren(RenrenApiConfig.renrenApiKey, RenrenApiConfig.renrenApiSecret, RenrenApiConfig.renrenAppID, LoginActivity.this); 
		ApiDemoInvoker.init(renren);
		handler = new Handler(); 
		loginBtn = (Button) findViewById(R.id.loginBtn); 
		logoutBtn = (Button) findViewById(R.id.logoutBtn); 
		loginText = (TextView) findViewById(R.id.loginText); 
		showLoginBtn(true); 
		} 
	//显示登录/退出按钮
	private void showLoginBtn(boolean flag){ 
		if(flag){ 
			loginBtn.setVisibility(View.VISIBLE); 
			logoutBtn.setVisibility(View.GONE); 
		} else { 
			loginBtn.setVisibility(View.GONE); 
			logoutBtn.setVisibility(View.VISIBLE); 
		}
	}
	
	/**
     * start the api list activity
     */
    private void startApiList() {
    	Intent intent = new Intent(this, ApiListActivity.class);
    	intent.putExtra(Renren.RENREN_LABEL, renren);
    	startActivity(intent);
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		renren.init(this);
	}

}
